package com.limetalks.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.limetalks.data.Category;
import com.limetalks.data.Comment;
import com.limetalks.data.Stream;
import com.limetalks.data.User;
import com.limetalks.util.GlobalStrings;

public class StreamDAO {
		
	private EntityManagerFactory emf;	
	
	public StreamDAO(EntityManagerFactory emf) {
		this.emf = emf;
	}
	
	public Stream findById(Integer streamId){
		EntityManager em = emf.createEntityManager();
		return em.find(Stream.class, streamId);
	}
	
	public void save(Stream stream){
		EntityManager em = emf.createEntityManager();
		em.getTransaction().begin();
		em.persist(stream);
		em.getTransaction().commit();
	}
	
	public List<Category> getAllCategories() {
		EntityManager em = emf.createEntityManager();
		Query getAllCategoriesQuery = em.createNamedQuery("getAllCategories");
		try {
			return getAllCategoriesQuery.getResultList();	 
		} catch (NoResultException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public List<Stream> findByMaster(User master) {
		EntityManager em = emf.createEntityManager();
		Query findByMasterQuery = em.createNamedQuery("findByMaster");
		findByMasterQuery.setParameter("master", master);
		try {
			return findByMasterQuery.getResultList();
		} catch (NoResultException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public List<Comment> findCommentByStream(Integer streamId) {
		EntityManager em = emf.createEntityManager();
		Query findByStreamQuery = em.createNamedQuery("findCommentsByStream");
		findByStreamQuery.setParameter("streamId", streamId);
		try {
			return findByStreamQuery.getResultList();
		} catch (NoResultException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public List<Stream> getAllStreams() {
		EntityManager em = emf.createEntityManager();
		Query getStreamsQuery = em.createNamedQuery("getAllStreams");
		try {
			return getStreamsQuery.getResultList();
		} catch (NoResultException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public void saveComment(Comment comment){
		EntityManager em = emf.createEntityManager();
		em.getTransaction().begin();
		em.persist(comment);
		em.getTransaction().commit();
	}
}
